package com.hj.runner;

import com.hj.factory.CaptchaTypeFactory;
import com.hj.util.ImageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author doudh
 * @date 2020/8/25
 * @description
 */
@Component
@Order(value = 1)
public class CaptchaInitRunner implements CommandLineRunner {

    private static Logger logger = LoggerFactory.getLogger(CaptchaInitRunner.class);

    /**
     * 滑动拼图底图路径
     */
    @Value("${captcha.jigsaw:classpath:images/jigsaw}")
    private String jigsawUrlOrPath;

    /**
     * 点选文字底图路径.
     */
    @Value("${captcha.pic-click:classpath:images/pic-click}")
    private String picclickUrlOrPath;

    @Override
    public void run(String... args) {
        logger.info(">>>>>>>>>>>>>>>初始化图片信息!<<<<<<<<<<<<<");
        initializeBaseMap(jigsawUrlOrPath, picclickUrlOrPath);
    }

    private static void initializeBaseMap(String jigsaw, String picClick) {
        ImageUtils.cacheBootImage(getResourcesImagesFile(jigsaw + "/original/*.png"),
            getResourcesImagesFile(jigsaw + "/slidingBlock/*.png"), getResourcesImagesFile(picClick + "/*.png"));
        CaptchaTypeFactory.init();
    }

    public static Map<String, String> getResourcesImagesFile(String path) {
        Map<String, String> imgMap = new HashMap<>();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] resources = resolver.getResources(path);
            for (Resource resource : resources) {
                byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
                String string = Base64Utils.encodeToString(bytes);
                String filename = resource.getFilename();
                imgMap.put(filename, string);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imgMap;
    }

}
